package com.yuyou.fn.controller;

import com.yuyou.fn.analyze.service.*;

import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.BeanUtils;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.common.util.Utils;

import com.yuyou.fn.educational.entity.Period;
import com.yuyou.fn.educational.service.IPeriodService;
import com.yuyou.fn.educational.vo.*;

import com.yuyou.fn.platform.entity.AreaTeam;
import com.yuyou.fn.platform.permission.DataPermission;
import com.yuyou.fn.platform.service.IAreaTeamService;
import com.yuyou.fn.platform.service.IOpenAuthService;
import com.yuyou.fn.report.vo.*;

import com.yuyou.fn.wage.service.IWageTeacherDollarsService;
import com.yuyou.fn.wage.vo.TeacherDollarsDetailVo;
import io.swagger.annotations.ApiOperation;

import io.swagger.annotations.ApiParam;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;

import java.util.*;


/**
 * Created by itachi on 2017/04/05.
 */
@Controller
@RequestMapping("/costCenter")
public class CostCenterApiController extends ApiBaseController {

    @Resource
    private ICostCenterService costCenterService;

    @Resource
    private IPeriodService periodService;

    @Resource
    private IAreaTeamService areaTeamService;

    @Resource
    private IOpenAuthService openAuthService;

    @Resource
    private IWageTeacherDollarsService wageTeacherDollarsService;

    @ApiOperation("浮动奖金人员名单")
    @RequestMapping(value = "/findEmployeeMessage",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<EmployeeMessageVo>> findEmployeeMessage( HttpServletRequest request){
        checkSign(request);
        TeacherQueryVo teacherQueryVo=new TeacherQueryVo();
        teacherQueryVo.setStatus(1);
        teacherQueryVo.setAccessTypes(Arrays.asList(0,1));
        return ReturnResult.success(costCenterService.findEmployeeMessage(teacherQueryVo));
    }

    @ApiOperation("咨询师新老生科数和金额")
    @RequestMapping(value = "/findNewOldStudentBranchAmount",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<NewOldStudentBranchAdvanceVo>> findNewOldStudentBranchAmount(@ApiParam("取数区域")@RequestParam(value = "areaTeamNames",required = false)String areaTeamNames,@ApiParam("开始支付时间 yyyy-MM-dd HH:mm:ss")@RequestParam("startPayTime")Date startPayTime, @ApiParam("结束支付时间 yyyy-MM-dd HH:mm:ss")@RequestParam("endPayTime") Date endPayTime,  HttpServletRequest request){
        checkSign(request);
        StudentRegDetailQueryVo studentRegDetailQueryVo=new StudentRegDetailQueryVo();
        studentRegDetailQueryVo.setStartPayTime(startPayTime);
        studentRegDetailQueryVo.setEndPayTime(endPayTime);
        studentRegDetailQueryVo.setAreaTeamIds(this.findAreaTeamIdsByAreaTeamNames(areaTeamNames));
        return ReturnResult.success(costCenterService.findNewOldStudentBranchAmount(studentRegDetailQueryVo));
    }

    @ApiOperation("班主任续读生科数金额")
    @RequestMapping(value = "/findSeqStepStudentBranchAmount",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<SeqStepStudentBranchAdvanceVo>> findSeqStepStudentBranchAmount(@ApiParam("格式：广州区域|2018暑假")@RequestParam("areaTeamPeriod") String areaTeamPeriod, @ApiParam("开始支付时间 yyyy-MM-dd HH:mm:ss")@RequestParam("startPayTime")Date startPayTime, @ApiParam("结束支付时间 yyyy-MM-dd HH:mm:ss")@RequestParam("endPayTime") Date endPayTime, HttpServletRequest request){

        checkSign(request);
        List<Long> periodIds=this.findPeriodIdsByAreaTeamPeriodsAreaTeamNames(areaTeamPeriod,null);
        if (Utils.checkListEmpty(periodIds)){
            throw new BusException("查询不到对应期数");
        }

        PeriodQueryRegVo periodQueryRegVo =new PeriodQueryRegVo();
        periodQueryRegVo.setPeriodIds(periodIds);

        RegRelativceQueryVo regRelativceQueryVo=new RegRelativceQueryVo();
        regRelativceQueryVo.setStartPayTime(startPayTime);
        regRelativceQueryVo.setEndPayTime(endPayTime);
        List<PeriodRelativeVo> periodRelativeVoList=periodService.findPeriodRelativeByPeriodIds(periodIds);
        List<Long> relativePeriodIds=new ArrayList<>();
        for (PeriodRelativeVo periodRelativeVo :periodRelativeVoList){
            relativePeriodIds.addAll(periodRelativeVo.getRelativePeriodIds());
        }
        regRelativceQueryVo.setPeriodIds(relativePeriodIds);
        regRelativceQueryVo.setPeriodRelativeVoList(periodRelativeVoList);

        return ReturnResult.success(costCenterService.findSeqStepStudentBranchAmount(regRelativceQueryVo,periodQueryRegVo));
    }



    @ApiOperation("期新老续科数")
    @RequestMapping(value = "/findPeriodStudentBranch",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<PeriodStudentBranchVo>> findPeriodStudentBranch(@RequestParam("areaTeamPeriods")String areaTeamPeriods,@RequestParam("areaTeamNames") String areaTeamNames, HttpServletRequest request){
        checkSign(request);
        return ReturnResult.success(costCenterService.findPeriodStudentBranch(this.findPeriodIdsByAreaTeamPeriodsAreaTeamNames(areaTeamPeriods,areaTeamNames)));
    }

    @ApiOperation("网报新老生招生提成")
    @RequestMapping(value = "/countBusTeamOlineNoCounselorBranch",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<NoCounselorBranchVo>> countBusTeamOlineNoCounselorBranch(@ApiParam("取数区域")@RequestParam(value = "areaTeamNames",required = false)String areaTeamNames,@ApiParam("开始支付时间 yyyy-MM-dd HH:mm:ss")@RequestParam("startPayTime")Date startPayTime, @ApiParam("结束支付时间 yyyy-MM-dd HH:mm:ss")@RequestParam("endPayTime") Date endPayTime, HttpServletRequest request){
        checkSign(request);
        StudentRegDetailQueryVo studentRegDetailQueryVo=new StudentRegDetailQueryVo();
        studentRegDetailQueryVo.setStartPayTime(startPayTime);
        studentRegDetailQueryVo.setEndPayTime(endPayTime);
        //studentRegDetailQueryVo.setRegFrom(0);
        studentRegDetailQueryVo.setAreaTeamIds(this.findAreaTeamIdsByAreaTeamNames(areaTeamNames));
        return ReturnResult.success(costCenterService.countBusTeamOlineNoCounselorBranch(studentRegDetailQueryVo));
    }

    @ApiOperation("咨询师新老续预收（基于生源类型）(线下)")
    @RequestMapping(value = "/findCounselorBranchAdvanceByStudentState",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<CounselorBranchAdvanceVo>> findCounselorBranchAdvanceByStudentState(@ApiParam("取数区域")@RequestParam(value = "areaTeamNames",required = false)String areaTeamNames,@ApiParam("开始支付时间 yyyy-MM-dd HH:mm:ss")@RequestParam("startPayTime")Date startPayTime, @ApiParam("结束支付时间 yyyy-MM-dd HH:mm:ss")@RequestParam("endPayTime") Date endPayTime,HttpServletRequest request){
        checkSign(request);
        StudentRegDetailQueryVo studentRegDetailQueryVo=new StudentRegDetailQueryVo();
        studentRegDetailQueryVo.setStartPayTime(startPayTime);
        studentRegDetailQueryVo.setEndPayTime(endPayTime);
        studentRegDetailQueryVo.setRegFrom(0);
        studentRegDetailQueryVo.setAreaTeamIds(this.findAreaTeamIdsByAreaTeamNames(areaTeamNames));
        return ReturnResult.success(costCenterService.findCounselorBranchAdvanceByStudentState(studentRegDetailQueryVo));
    }

    @ApiOperation("消耗")
    @RequestMapping(value = "/findBusTeamConsume",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<BusTeamPeriodConsumeVo>> findBusTeamConsume(@RequestParam("areaTeamPeriods")String areaTeamPeriods, HttpServletRequest request){
        checkSign(request);
        List<Long> periodIds=this.findPeriodIdsByAreaTeamPeriodsAreaTeamNames(areaTeamPeriods,null);

        return ReturnResult.success(costCenterService.findBusTeamPeriodConsumeList(periodIds));
    }


    @ApiOperation("课酬设置老师课程信息")
    @RequestMapping(value = "/findEmployeeCourse",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<EmployeeCourseVo>> findEmployeeCourse(@ApiParam("取数区域")@RequestParam(value = "areaTeamNames",required = false)String areaTeamNames,@ApiParam("开始时间 yyyy-MM-dd HH:mm:ss")@RequestParam("startDate")Date startDate, @ApiParam("结束时间 yyyy-MM-dd HH:mm:ss")@RequestParam("endDate") Date endDate, HttpServletRequest request){
        checkSign(request);
        ClassLectureDetailQueryVo classLectureDetailQueryVo=new ClassLectureDetailQueryVo();
        classLectureDetailQueryVo.setStartDate(startDate);
        classLectureDetailQueryVo.setEndDate(endDate);
        classLectureDetailQueryVo.setAreaTeamIds(this.findAreaTeamIdsByAreaTeamNames(areaTeamNames));
        return ReturnResult.success(costCenterService.findEmployeeCourse(classLectureDetailQueryVo));
    }

    @ApiOperation("考勤信息")
    @RequestMapping(value = "/findEmployeeAttendance",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<EmployeeAttendanceVo>> findEmployeeAttendance(@ApiParam("取数区域")@RequestParam(value = "areaTeamNames",required = false)String areaTeamNames,@ApiParam("开始时间 yyyy-MM-dd HH:mm:ss")@RequestParam("startDate")Date startDate, @ApiParam("结束时间 yyyy-MM-dd HH:mm:ss")@RequestParam("endDate") Date endDate, HttpServletRequest request){
        checkSign(request);
        AttendClassLectureQueryVo attendClassLectureQueryVo=new AttendClassLectureQueryVo();
        attendClassLectureQueryVo.setAreaTeamIds(this.findAreaTeamIdsByAreaTeamNames(areaTeamNames));
        attendClassLectureQueryVo.setStartClassDate(startDate);
        attendClassLectureQueryVo.setEndClassDate(endDate);
        return ReturnResult.success(costCenterService.findEmployeeAttendance(attendClassLectureQueryVo));
    }

    @ApiOperation("兼职基础信息")
    @RequestMapping(value = "/findTeacherDollarsDetailList",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<TeacherDollarsDetailVo>> findTeacherDollarsDetailList( @RequestParam("startDate")Date startDate,@RequestParam("endDate")Date endDate, HttpServletRequest request) throws Exception{
        checkSign(request);
        ClassLectureDetailQueryVo classLectureDetailQueryVo=new ClassLectureDetailQueryVo();
        classLectureDetailQueryVo.setJobNature(1);
        classLectureDetailQueryVo.setStatuses(Arrays.asList(1,3));
        classLectureDetailQueryVo.setStartClassDate(startDate);
        classLectureDetailQueryVo.setEndClassDate(endDate);
        //classLectureDetailQueryVo.setPeriodIds(this.findPeriodIdsByAreaTeamPeriodsAreaTeamNames(areaTeamPeriods,areaTeamNames));
        List<TeacherDollarsDetailVo> teacherDollarsDetailList = wageTeacherDollarsService.findAllTeacherDollarsDetailList(null, classLectureDetailQueryVo, 1);
        return ReturnResult.success(teacherDollarsDetailList);
    }

    private List<Long> findAreaTeamIdsByAreaTeamNames(String areaTeamNames){
        if (StringUtils.isNotEmpty(areaTeamNames)){
            List<String> areaTeamNameList=Utils.toStringList(areaTeamNames);
            List<AreaTeam> areaTeamList=areaTeamService.findAreaTeamByNames(areaTeamNameList);
            List<Long> areaTeamIds = BeanUtils.toList(areaTeamList, "areaTeamId");
            if (Utils.checkListEmpty(areaTeamIds) || areaTeamIds.size()<areaTeamNameList.size()){
                throw new BusException("有些区域不存在");
            }
            return areaTeamIds;
        }
        return Collections.EMPTY_LIST;
    }

    private void checkSign(HttpServletRequest request){
        String appId=request.getHeader("appId");
        String sign=request.getHeader("sign");
        String times=request.getHeader("times");
        Date date=new Date(Long.parseLong(times));
        Date preDate= TimeUtils.changeDateByNum(new Date(),-1);
        if (date.before(preDate)){
            throw new BusException("签名过期");
        }
        if (StringUtils.isEmpty(appId) || StringUtils.isEmpty(sign) || StringUtils.isEmpty(times)){
            throw new BusException("缺少参数");
        }
        String secretKey = openAuthService.findSecretKeyForAppId(appId);
        if(!sign.toLowerCase().equals(DigestUtils.md5Hex(appId  +secretKey+ times ).toLowerCase())){
            throw new BusException("检验失败");
        }
    }

    private List<Long> findPeriodIdsByAreaTeamPeriodsAreaTeamNames(String areaTeamPeriods,String areaTeamNames){
        String[] areaTeamPeriodsArray=areaTeamPeriods.split("[;；]");
        Map<String,List<String>> map=new HashMap<>();
        List<String> areaTeamNameList=Utils.toStringList(areaTeamNames);
        for (String areaTeamPeriod:areaTeamPeriodsArray){
            String[] areaTeamPeriodArray=areaTeamPeriod.split("\\|");
            String areaTeamName=areaTeamPeriodArray[0];
            if (!areaTeamNameList.isEmpty() && !areaTeamNameList.contains(areaTeamName)){
                continue;
            }
            List<String> list=map.get(areaTeamName);
            if (list==null){
                list=new ArrayList<>();
                map.put(areaTeamName,list);
            }
            list.add(areaTeamPeriodArray[1]);
        }
        List<Long> periodIds=new ArrayList<>();
        for (Map.Entry<String,List<String>> entry:map.entrySet()){
            periodIds.addAll(this.findPeriodIdsByAreaTeamNamePeriodNames(entry.getKey(),entry.getValue()));
        }
        return periodIds;
    }

    private List<Long> findPeriodIdsByAreaTeamNamePeriodNames(String areaTeamName,List<String> periodNames){
        AreaTeam areaTeam=areaTeamService.findAreaTeamByName(areaTeamName);
        List<Period> periodList=periodService.findByAreaTeamIdsAndNames(Arrays.asList(areaTeam.getAreaTeamId()),periodNames);
        List<Long> periodIds = BeanUtils.toList(periodList, "periodId");
        return periodIds;
    }

/*    private List<Long> findCurrentPeriodIdsByAreaTeamNames(String areaTeamPeriods,String areaTeamNames){
        List<AreaTeam> areaTeamList=areaTeamService.findAreaTeamByNames(Utils.toStringList(areaTeamNames));
        List<Period> periods = periodService.findCurrentPeriodsByAreaTeamIds(BeanUtils.toList(areaTeamList, "areaTeamId"));
        if (areaTeamList.size()!=periods.size() || periods.size()==0){
            throw new BusException("存在区域没有当前期");
        }
        return BeanUtils.toList(periods,"periodId");
    }*/


}
